import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { MenuItem } from '@/types/menu'
import type { AppSettings } from '@/types/settings'
import { getMenuListApi } from '@/api/menu'
import { getSettingsApi, updateSettingsApi } from '@/api/settings'
import { unifiedSettings } from '@/config/unified-settings'

export const useAppStore = defineStore('app', () => {
  // 状态
  const sidebarCollapsed = ref(false)
  const menuList = ref<MenuItem[]>([])
  const breadcrumbs = ref<MenuItem[]>([])
  const loading = ref(false)
  const theme = ref<'light' | 'dark'>('light')
  const language = ref('zh-cn')
  const pageSize = ref(10)
  
  // 系统设置 - 使用统一设置配置
  const settings = ref<AppSettings>({ ...unifiedSettings })
  
  const settingsLoading = ref(false)
  const settingsChanged = ref(false)

  // 切换侧边栏
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }

  // 设置侧边栏状态
  const setSidebarCollapsed = (collapsed: boolean) => {
    sidebarCollapsed.value = collapsed
  }

  // 获取菜单列表
  const getMenuList = async () => {
    try {
      loading.value = true
      const response = await getMenuListApi()
      menuList.value = (response as MenuItem[]) || []
      return response
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error('获取菜单列表失败:', error)
      return []
    } finally {
      loading.value = false
    }
  }

  // 设置面包屑
  const setBreadcrumbs = (breadcrumbList: MenuItem[]) => {
    breadcrumbs.value = breadcrumbList
  }

  // 设置主题
  const setTheme = (themeValue: 'light' | 'dark') => {
    theme.value = themeValue
    // 这里可以添加主题切换的逻辑
    document.documentElement.setAttribute('data-theme', themeValue)
  }

  // 设置语言
  const setLanguage = (lang: string) => {
    language.value = lang
    // 这里可以添加语言切换的逻辑
  }

  // 设置页面大小
  const setPageSize = (size: number) => {
    pageSize.value = size
  }
  
  // 计算属性
  const isDarkMode = computed(() => theme.value === 'dark')
  const currentLocale = computed(() => language.value)
  
  // 获取设置
  const getSettings = async () => {
    try {
      settingsLoading.value = true
      const response = await getSettingsApi()
      settings.value = { ...settings.value, ...response }
      return response
    } catch (error) {
      console.error('获取设置失败:', error)
      throw error
    } finally {
      settingsLoading.value = false
    }
  }
  
  // 更新设置
  const updateSettings = async (newSettings: Partial<AppSettings>) => {
    try {
      settingsLoading.value = true
      await updateSettingsApi(newSettings)
      settings.value = { ...settings.value, ...newSettings }
      settingsChanged.value = true
      
      // 应用设置变更
      applySettings(newSettings)
      
      return true
    } catch (error) {
      console.error('更新设置失败:', error)
      throw error
    } finally {
      settingsLoading.value = false
    }
  }
  
  // 更新单个设置项
  const updateSetting = (path: string, value: unknown) => {
    const keys = path.split('.')
    let current: Record<string, unknown> = settings.value as Record<string, unknown>
    
    for (let i = 0; i < keys.length - 1; i++) {
      if (!current[keys[i]]) {
        current[keys[i]] = {}
      }
      current = current[keys[i]] as Record<string, unknown>
    }
    
    current[keys[keys.length - 1]] = value
    settingsChanged.value = true
    
    // 应用设置变更
    applySettings({ [keys[0]]: settings.value[keys[0] as keyof AppSettings] })
  }
  
  // 应用设置变更
  const applySettings = (newSettings: Partial<AppSettings>) => {
    // 应用主题设置
    if (newSettings.theme) {
      const { mode, primaryColor, borderRadius } = newSettings.theme
      if (mode && mode !== 'auto') {
        setTheme(mode as 'light' | 'dark')
      }
      if (primaryColor) {
        document.documentElement.style.setProperty('--el-color-primary', primaryColor)
      }
      if (borderRadius) {
        const radiusMap = {
          none: '0px',
          small: '2px',
          medium: '4px',
          large: '8px'
        }
        document.documentElement.style.setProperty('--el-border-radius-base', radiusMap[borderRadius])
      }
    }
    
    // 应用界面设置
    if (newSettings.interface) {
      const { sidebarCollapsed: collapsed, pageSize: size } = newSettings.interface
      if (collapsed !== undefined) {
        setSidebarCollapsed(collapsed)
      }
      if (size) {
        setPageSize(size)
      }
    }
    
    // 应用语言设置
    if (newSettings.language) {
      const { locale } = newSettings.language
      if (locale) {
        setLanguage(locale)
      }
    }
  }
  
  // 重置设置
  const resetSettings = (_category?: string) => {
    // 这里可以实现重置到默认设置的逻辑
    settingsChanged.value = false
  }
  
  // 保存设置到本地存储
  const saveSettingsToLocal = () => {
    localStorage.setItem('app-settings', JSON.stringify(settings.value))
  }
  
  // 从本地存储加载设置
  const loadSettingsFromLocal = () => {
    try {
      const saved = localStorage.getItem('app-settings')
      if (saved) {
        const parsedSettings = JSON.parse(saved)
        settings.value = { ...settings.value, ...parsedSettings }
        applySettings(parsedSettings)
      }
    } catch (error) {
      console.error('加载本地设置失败:', error)
    }
  }

  // 初始化应用
  const initApp = () => {
    // 从本地存储恢复设置
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark'
    if (savedTheme) {
      setTheme(savedTheme)
    }
    
    const savedLanguage = localStorage.getItem('language')
    if (savedLanguage) {
      setLanguage(savedLanguage)
    }
    
    const savedPageSize = localStorage.getItem('pageSize')
    if (savedPageSize) {
      setPageSize(Number(savedPageSize))
    }
  }

  return {
    // 状态
    sidebarCollapsed,
    menuList,
    breadcrumbs,
    loading,
    theme,
    language,
    pageSize,
    settings,
    settingsLoading,
    settingsChanged,
    
    // 计算属性
    isDarkMode,
    currentLocale,
    
    // 方法
    toggleSidebar,
    setSidebarCollapsed,
    getMenuList,
    setBreadcrumbs,
    setTheme,
    setLanguage,
    setPageSize,
    getSettings,
    updateSettings,
    updateSetting,
    applySettings,
    resetSettings,
    saveSettingsToLocal,
    loadSettingsFromLocal,
    initApp
  }
})
